<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>标题：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.title"
                        clearable
                        placeholder="标题"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <label>行业分类：</label>
                <el-select
                    placeholder="行业分类"
                    @change="choseSearchExam"
                    v-model="queryData.industryId"
                    clearable
                >
                    <el-option
                        v-for="item in industryOptions"
                        :key="item.name"
                        :label="item.name"
                        :value="item.id"

                    >
                    </el-option>
                </el-select>
            </div>
            <div class="search-item">
                <label>所属考试：</label>
                <el-select
                    v-model="queryData.examId"
                    placeholder="考试"
                    filterable
                    clearable
                >
                    <el-option
                        v-for="item in examOptions"
                        :key="item.name"
                        :label="item.name"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索</el-button
                >
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                style="margin-bottom: 2em"
                @click="go('advertisementAdd')"
            >新增广告</el-button
            >
            <el-button
                type="warning"
                style="margin-bottom: 2em"
                icon="el-icon-lock"
                :disabled="selectDisable"
                @click="batchDelete()"
            >批量删除</el-button
            >
        </div>

        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
                @selection-change="tableSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column prop="title" label="标题" width="120">
                </el-table-column>
                <el-table-column
                    prop="examName"
                    label="所属考试"
                    min-width="100"
                >
                </el-table-column>
                <el-table-column
                    prop="industryName"
                    label="所属行业"
                    min-width="100"
                >
                </el-table-column>

                <el-table-column prop="sort" label="排序" min-width="100">
                </el-table-column>
                <el-table-column prop="introduction" label="简介" width="120">
                </el-table-column>
                <el-table-column prop="positionCode" label="广告位code" width="120">
            </el-table-column>
                <el-table-column label="客户端" prop="type">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.clientType===0" type="success"
                        >PC</el-tag
                        >
                        <el-tag v-if="scope.row.clientType===1" type="warning"
                        >APP</el-tag
                        >
                    </template>
                </el-table-column>


                <el-table-column
                    prop="createdName"
                    label="创建人"
                    min-width="100"
                >
                </el-table-column>
                <el-table-column
                    prop="createdTime"
                    label="创建时间"
                    min-width="100"
                >
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="260"
                    align="center"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            size="mini"
                            :loading="scope.row.opLoading"
                            @click="go('advertisementAdd?id=' + scope.row.id)"
                        >编辑
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            class="danger"
                            type="text"
                            icon="el-icon-delete"
                            size="mini"
                            :loading="scope.row.opLoading"
                            @click="
                                tableDelete(
                                    '/advertisement/delete',
                                    {
                                        id: scope.row.id
                                    },
                                    true
                                )
                            "
                        >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                background
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>


    </div>
</template>

<script>
import { fetchClassesAll, fetchRoleAllActionCode } from "@/api/user.js";
import { batchResourcesUpload } from "@/api/course.js";
import { TablePage } from "@/layout/mixin/iVue.js";
import { ossUpload } from "@/utils/file.js";
import { mapState } from "vuex";
import { treeList2Tree } from "@/utils/index.js";
import {
    fetchCategoryChildren,
    fetchCategoryFirstStage,
    fetchClassificationChildren,
    fetchClassificationFirst,
    getCourseChapters,
    fetchArticleColumnFirst,
    fetchArticleColumnChildren
} from "@/api/course.js";
//lyh-update

import { get, put, post, fetchDelete } from "@/api/request";
import resourceShow from "@/components/resource/resourceShow";

export default {
    name: "MaterialInfoBaseSetting",
    components: {
        resourceShow
    },
    mixins: [TablePage],
    async asyncData(context) {
        return Promise.resolve().then(() => {
            const { app, query } = context;
            this.courseId = context.route.query.courseId;
            console.log("courseId", this.courseId);
        });
    },
    data() {
        return {
            industryOptions: [],
            examOptions: [],
            articleCategoryId: "",
            categoryOptions: [],
            courseId: "0",
            activeResource: {},
            dialogWidth: "",
            dialogLeft: "",
            dialogHeight: "",
            imgFlag: false,
            pdfFlag: false,
            previewFlag: false,
            previewPdf: null,
            previewImg: null,
            checkAll: false,
            selectCheck: [{ index: "" }],
            uploadGroupId: null,
            queryData: {
                examId:null,
                searchCount: true,
                articleColumnId: null
            },
            categoryId: 1,
            key: 0,
            groupKey: 0,
            initAddForm: {
                id: null,
                name: null,
                remark: null,
                actionCodes: []
            },
            actions: null,
            actionSearch: null,
            fileList: [],
            file: null,
            addOrUpdateflag: false,
            updateVisible: false,
            base64Header: null,
            showProgress: false,
            articleColumnProps: {
                lazy: true,
                checkStrictly: true,
                lazyLoad: this.getArticleColumnSta
            },
            classificationProps: {
                lazy: true,
                checkStrictly: true,
                lazyLoad: this.getSta
            },
            categoryProps: {
                lazy: true,
                addOrUpdateflag: false,
                checkStrictly: false,
                classificationId: null,
                lazyLoad(node, resolve) {
                    const { level } = node;
                    if (!node.data) {
                        fetchCategoryFirstStage().then(res => {
                            const nodes = Array.from(res).map(item => {
                                return {
                                    value: item.id,
                                    label: `${item.name}`,
                                    leaf:
                                        level >=
                                        (item.children.length > 0 ? 1 : 0)
                                };
                            });
                            resolve(nodes);
                        });
                    } else {
                        fetchCategoryChildren({ id: node.data.value }).then(
                            res => {
                                const nodes = Array.from(res).map(item => {
                                    return {
                                        value: item.id,
                                        label: `${item.name}`,
                                        leaf:
                                            level >=
                                            (item.children.length > 0
                                                ? level + 1
                                                : 0)
                                    };
                                });
                                resolve(nodes);
                            }
                        );
                    }
                }
            }
        };
    },
    computed: {
        ...mapState({
            status: state => state.status.roleSystem
        })
    },
    watch: {
        actionSearch(val) {
            this.$refs.tree.filter(val);
        }
    },
    created() {
        this.getArticleCategory();
        this.getIndustryOptions();
        this.getExamOptions();
    },
    methods: {
        choseSearchExam(){
            this.queryData.examId = null
            get("/exam/exam/list", {"industryId": this.queryData.industryId,"size": 1000}).then(res => {
                this.examOptions = res;
            });
        },
        getIndustryOptions() {
            get("/exam/industry/list",{size: 1000}).then(res => {
                this.industryOptions = res;
            });
        },
        getExamOptions() {
            get("/exam/exam/list").then(res => {
                console.log("res", res);
                this.examOptions = res;
            });
        },
        handResourceChange(value) {
            if (typeof value !== "undefined") {
                var len = value.length - 1;
                this.classificationId = value[len];
                this.queryData.resourceGroupId = [];
                // ++this.key;
                ++this.groupKey;
            }
        },
        changeCategory() {
            ++this.groupKey;
        },
        getArticleCategory() {
            // get("/course/article/category/list").then(res => {
            //     console.log("res", res);
            //     this.categoryOptions = res;
            // });
        },
        coverResourceSize(size) {
            var resSzie = "";
            if (size < 1024 * 1024) {
                resSzie = (size / 1024).toFixed(2) + "K";
            } else {
                resSzie = (size / 1024 / 1024).toFixed(2) + "M";
            }
            return resSzie;
        },

        closeDialog() {
            this.uploadGroupId = null;
            this.search();
        },
        closePreview() {
            this.previewImg = null;
            this.previewPdf = null;
        },
        handleCheckAllChange(val) {
            for (let i = 0; i < this.resourceData.list.length; i++) {
                if (!this.resourceData.list[i].resourceUrl) {
                    this.resourceData.list[i].singleCheck = val;
                }
            }
        },
        handleCheckedSingleChange(item) {
            if (item.resourceUrl) {
                this.$message({
                    message: "这条资源已上传，请勿重复上传",
                    type: "warning"
                });
            }
        },
        handleGroupId(value) {
            if (value !== null && value !== undefined) {
                let cLength = value.length;
                value = value[cLength - 1];
            }
            this.uploadGroupId = value;
        },
        handelChangeGroupId(index, value) {},
        async batchDelete() {
            await this.$confirm("确定删除这些广告吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    fetchDelete("/advertisement/batch-delete", {
                        ids: this.tableSelect
                    }).then(res => {
                        this.search();
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
        },
        batchUploadDelete() {
            let updateArray = [];
            for (let i = 0; i < this.resourceData.list.length; i++) {
                if (this.resourceData.list[i].singleCheck !== true) {
                    updateArray.push(this.resourceData.list[i]);
                }
            }
            this.resourceData.list = updateArray;
            this.fileList = updateArray;
        },

        async uploadFiles(fileList) {
            let selectFiles = fileList;
            let promises = [];
            let setFileList = [];
            var num = 0;
            for (let i = 0; i < selectFiles.length; i++) {
                if (i !== 0 && i % 3 === 0) {
                    await Promise.all(promises).then(res => {
                        this.setResourceData(res, setFileList, num);
                    });
                    promises = [];
                    setFileList = [];
                    num++;
                }
                let file = selectFiles[i].raw;
                promises.push(
                    ossUpload("cdn", file.name, file, p => {
                        this.showProgress = true;
                        this.resourceData.list[i].percentage = p * 100;
                    })
                );
                setFileList.push(selectFiles[i]);
            }
            await Promise.all(promises).then(res => {
                this.setResourceData(res, setFileList, num);
            });
            this.$forceUpdate;
        },

        setResourceData(res, setFileList, num) {
            for (let i = 0; i < setFileList.length; i++) {
                // let index = setFileList[i].index
                let index = i + num * 3;
                this.resourceData.list[index].resourceUrl = res[i];
                let f = setFileList[i];
                let name = f.name;
                let str = name.split(".");
                this.resourceData.list[index].resourceType = str[1];
                this.resourceData.list[
                    index
                    ].resourceGroupId = this.uploadGroupId;
                this.resourceData.list[index].singleCheck = false;
                this.resourceData.list[index].checkUpload = false;
            }
        },
        batchUpload(resourceData) {
            let resourceMoles = {};
            let resourceArray = [];
            let obj = {};
            for (let i = 0; i < resourceData.list.length; i++) {
                const element = resourceData.list[i];
                let resource = {};
                resource.resourceName = element.name;
                resource.resourceUrl = element.resourceUrl;
                resource.resourceType = element.resourceType;
                resource.resourceSize = element.size;
                resource.resourceGroupId = element.resourceGroupId;
                resourceArray.push(resource);
                if (!element.name) {
                    this.$message.error("第" + i + "条资源，名字不能为空");
                    return;
                }
                if (!element.resourceGroupId) {
                    this.$message.error(
                        "第" +
                        i +
                        "条资源：" +
                        element.name +
                        "没有选择资源分组"
                    );
                    return;
                }
                if (!element.resourceUrl) {
                    this.$message.error(
                        "第" +
                        i +
                        "条资源：" +
                        element.name +
                        "没有选择资源地址"
                    );
                    return;
                }
            }
            resourceMoles.list = resourceArray;
            batchResourcesUpload(resourceMoles).then(res => {
                if (res) {
                    (this.resourceData = {}),
                        (this.fileList = []),
                        this.$forceUpdate();
                    this.$message({
                        showClose: true,
                        message: "导入成功",
                        type: "success"
                    });
                } else {
                    this.$message.error("导入失败，请检查后重试");
                }
            });
        },
        deleteFile(index) {
            this.fileList.splice(index, 1);
        },
        uploadChange(file, fileList) {
            this.fileList = fileList;
            const fileLists = fileList;
            for (let i = 0; i < fileLists.length; i++) {
                fileLists[i].opLoading = true;
                // fileLists[i].singleCheck = false
                fileLists[i].resourceGroupId = this.uploadGroupId;
                fileLists[i].checkUpload = true;
            }
            this.resourceData.list = fileLists;
        },
        clickAddResource() {
            (this.addOrUpdateflag = true), (this.updateVisible = true);
            //   this.clickAdd('添加资源', this.selectAllAction);
        },
        clickEdit(val) {
            this.addOrUpdateflag = false;
            this.clickSimpleEdit(val, "资源编辑", val);
        },

        search() {
            //     if (
            //         this.queryData.articleColumnId !== null &&
            // this.queryData.articleColumnId !== undefined
            //     ) {
            //         let qlength = this.queryData.articleColumnId.length;
            //         this.queryData.articleColumnId = this.queryData.articleColumnId[
            //             qlength - 1
            //         ];
            //     }

            this.loadTable("/advertisement/page", this.queryData);
        },

        changeUserStatus(id, status) {
            // data.opLoading = true;
            put(`/course/resources/released/${status}/${id}`);
            // .then(res => {
            //     data.userStatus = status ? "normal" : "lock";
            // })
            // .finally(() => {
            //     data.opLoading = false;
            // });
        },
        handChange(value) {
            this.queryData.classificationId = [];
            ++this.key;
            if (value !== null) {
                let nodesObj = this.$refs["cascader"].getCheckedNodes()[0];
                this.courseType = nodesObj.data.type;
                this.categoryId = value[0];
                // this.subjectDisabled = false;
            } else {
                // this.subjectDisabled = true;
            }
        },

        getArticleColumnSta(node, resolve) {
            const { level } = node;
            if (!node.data) {
                fetchArticleColumnFirst({
                    articleCategoryId: this.articleCategoryId
                }).then(res => {
                    const nodes = Array.from(res).map(item => {
                        return {
                            value: item.id,
                            label: `${item.name}`,
                            leaf: level >= (item.children.length > 0 ? 1 : 0)
                        };
                    });
                    resolve(nodes);
                });
            } else {
                fetchArticleColumnChildren({ id: node.data.value }).then(
                    res => {
                        const nodes = Array.from(res).map(item => {
                            return {
                                value: item.id,
                                label: `${item.name}`,
                                leaf:
                                    level >=
                                    (item.children.length > 0 ? level + 1 : 0)
                            };
                        });
                        resolve(nodes);
                    }
                );
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.top {
    width: 100%;
    height: 100%;
    //   background: red;
    display: flex;
    flex-direction: column;
}
.action-bar {
    width: 100%;
    height: 60px;
    border-bottom: 1px;
    //   background: pink;
    display: flex;
    flex-direction: row;
    align-items: center;
}
.action-bar-add {
    width: 100px;
    height: 50px;
    border-bottom: 1px;
    //   background: rgb(170, 129, 136);
    display: flex;
    align-items: center;
    justify-content: center;
}
.action-bar-group {
    width: 160px;
    height: 50px;
    border-bottom: 1px;
    //   background: rgb(158, 120, 126);
    display: flex;
    align-items: center;
    justify-content: center;
}
.action-list {
    width: 100%;
    height: 380px;
    border-bottom: 1px;
    //   background: rgb(167, 123, 130);
    display: flex;
    flex-direction: column;
}
.action-bottom {
    width: 100%;
    height: 60px;
    border-bottom: 1px;
    //   background: rgb(131, 154, 228);
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
}
.action-bottom-upload {
    width: 160px;
    height: 50px;
    border-bottom: 1px;
    //   background: rgb(170, 129, 136);
    display: flex;
    align-items: center;
    justify-content: center;
}
.action-list-top {
    width: 100%;
    height: 52px;
    border-bottom: 1px;
    //   background: rgb(167, 123, 130);
    display: flex;
}
.action-list-middle {
    width: 100%;
    height: 300px;
    //   border-bottom: 1px;
    //   background: rgb(167, 123, 130);
    display: flex;
    flex-direction: column;
}
.action-list-form {
    width: 100%;
    height: 38px;
    border-bottom: 1px;
    //   background: rgb(167, 123, 130);
}
.action-column {
    width: 100%;
    height: 30px;
    border-bottom: 1px;
    //   background: rgb(167, 123, 130);
    display: flex;
    flex-direction: row;
}
.action-column-item {
    width: 100%;
    height: 50px;
    //   background: rgb(167, 123, 130);
    display: flex;
    flex-direction: row;
    text-align: center;
    align-items: center;
    justify-content: space-between;
    border-right: 1px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
    border-top: 1px solid #dfe6ec;
}
.action-check {
    width: 20%;
    height: 52px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.form-item {
    width: 14%;
    height: 62%;
    border-right: 1px solid #dfe6ec;
    //   background: red;
    display: flex;
    flex-direction: row;
    margin: 0 auto;
    text-align: center;
    // align-items: center;
    //   border-bottom: 1px solid #dfe6ec;
}
.form-item-name {
    width: 16%;
    height: 62%;
    border-right: 1px solid #dfe6ec;
    //   background: red;
    display: flex;
    flex-direction: row;
    margin: 0 auto;
    text-align: center;
    // align-items: center;
    //   border-bottom: 1px solid #dfe6ec;
}
.form-item-progress {
    width: 8%;
    height: 78%;
    border-right: 1px solid #dfe6ec;
    //   background: red;
    display: flex;
    flex-direction: row;
    margin: 0 auto;
    text-align: center;
    // align-items: center;
    //   border-bottom: 1px solid #dfe6ec;
}
.el-form-item--mini .el-form-item__content {
    line-height: 37px !important;
}
.form-preview-pdf {
    width: 980px;
    height: 780px;
}
.form-preview-img {
    width: 160px;
    height: 160px;
}
.widthImg {
    width: 40%;
    height: 60%;
    display: flex;
    justify-content: center;
}
.widthPdf {
    width: 60%;
    height: 60%;
    display: flex;
    justify-content: center;
}

.update-form-item {
    width: 380px;
    //   margin-left: 20px;
    display: flex;
    flex-wrap: wrap;
}
.update-forms {
    width: 1200px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    //   justify-content: space-between;
}
.resourceShow {
    width: 60%;
    height: 60%;
}

</style>
